//
//  CYFinanceInfoViewController.m
//  cyjf
//
//  Created by tauCross on 2018/1/23.
//  Copyright © 2018年 Auto Financing. All rights reserved.
//

#import "CYFinanceInfoViewController.h"

#import "CYProfitsCalculatorView.h"
#import "CYEvaluateView.h"

#import "CYFinanceDetailViewController.h"
#import "CYFinanceDetailViewModel.h"
#import "CYFinanceInvestViewController.h"
#import "CYMainController.h"

#import "CYGlobalTimerManager.h"

#import <WebKit/WebKit.h>



@interface CYFinanceInfoViewController ()

@property(nonatomic, strong)CYFinanceDetailViewModel *viewModel;
@property(nonatomic, assign)CYFinanceDetailStatus status;

@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, strong)UIButton *tryButton;
@property(nonatomic, strong)UIButton *statusButton;
@property(nonatomic, strong)UIView *bottomLine;

@property(nonatomic, assign)BOOL loading;
@property(nonatomic, assign)BOOL evaluated;

@end


@implementation CYFinanceInfoViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.bottomView = [[UIView alloc] init];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomView];
    {
        self.bottomLine = [UIView cy_lineWithColor:HEXCOLOR(@"f6f6f6")];
        [self.bottomView addSubview:self.bottomLine];
        
        self.tryButton = [[UIButton alloc] init];
        [self.tryButton setImage:(SCREEN_HEIGHT == 812.0) ? CYImage(@"finance_detail_try_x") : CYImage(@"finance_detail_try") forState:UIControlStateNormal];
        [self.tryButton addTarget:self action:@selector(onTryButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.tryButton];
        
        self.statusButton = [[UIButton alloc] init];
        [self.statusButton setTitleColor:HEXCOLOR(@"FFFFFF") forState:UIControlStateNormal];
        [self.statusButton setTitleColor:HEXCOLOR(@"FFFFFF") forState:UIControlStateDisabled];
        self.statusButton.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        [self.statusButton addTarget:self action:@selector(onStatusButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.statusButton];
    }
    
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
        @strongify(self);
        [self onReceiveApplicationDidBecomeActiveNotification];
    }];
    
    [self refreshStatusButton];
    [CYStandardGlobalTimerManager addTarget:self withBlock:^{
        @strongify(self);
        [self refreshStatusButton];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.webView.height = self.webView.height - SAFE_BOTTOM_HEIGHT;
    
    self.bottomView.width = self.view.width;
    self.bottomView.height = SAFE_BOTTOM_HEIGHT;
    self.bottomView.left = 0;
    self.bottomView.bottom = self.view.height;
    {
        self.bottomLine.width = self.bottomView.width;
        self.bottomLine.height = 1 / SCREEN_SCALE;
        self.bottomLine.left = 0;
        self.bottomLine.bottom = 0;
        
        self.tryButton.width = self.bottomView.height;
        self.tryButton.height = self.bottomView.height;
        self.tryButton.left = 0;
        self.tryButton.top = 0;
        
        self.statusButton.width = self.bottomView.width - self.tryButton.right;
        self.statusButton.height = self.bottomView.height;
        self.statusButton.left = self.tryButton.right;
        self.statusButton.top = 0;
    }
}

- (void)loadDataFromServer
{
    if(self.loading)
    {
        return;
    }
    self.loading = YES;
    @weakify(self);
    [CYStandardDataAPI project_detailWithID:self.fid complete:^(CYResponse *response) {
        @strongify(self);
        
        if(response.code == 0)
        {
            CYDataAPIFinanceModel *apiModel = [CYDataAPIFinanceModel mj_objectWithKeyValues:response.content];
            self.viewModel = [CYFinanceDetailViewModel modelWithAPIModel:apiModel];
            [self refreshStatusButton];
        }
        else
        {
            if(self.viewModel == nil)
            {
                [SVProgressHUD showErrorWithStatus:response.message];
            }
        }
        self.loading = NO;
    }];
    
    [CYStandardDataAPI riskEvaluate_getRiskByTokenWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            if(response.content)
            {
                self.evaluated = YES;
                return;
            }
        }
        self.evaluated = NO;
    }];
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

#pragma mark - Action
- (void)investAction
{
    if(self.evaluated)
    {
        if(SAFE_NUMBER(self.viewModel.apiModel.notCanBuy).integerValue != 0)
        {
            [SVProgressHUD showInfoWithStatus:SAFE_STRING(self.viewModel.apiModel.notCanBuyDesc)];
        }
        else
        {
            CYFinanceInvestViewController *financeInvestViewController = [[CYFinanceInvestViewController alloc] init];
            financeInvestViewController.fid = self.fid;
            [self.navigationController pushViewController:financeInvestViewController animated:YES];
        }
    }
    else
    {
        @weakify(self);
        CYEvaluateView *view = [[CYEvaluateView alloc] init];
        view.evaluateAction = ^{
            @strongify(self);
            CYWebViewController *webViewController = [[CYWebViewController alloc] init];
            webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/risk_exam.html?from=1"];
            [self.navigationController pushViewController:webViewController animated:YES];
        };
        [view show];
    }
}

- (void)showLogInAction
{
    [[CYMainController standardController] showLogIn];
}

#pragma mark - Control Events
- (void)onTryButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0027];
    if(self.viewModel)
    {
        CYProfitsCalculatorView *view = [[CYProfitsCalculatorView alloc] init];
        view.rate = @(SAFE_NUMBER(self.viewModel.apiModel.userInterest).doubleValue / 100 + SAFE_NUMBER(self.viewModel.apiModel.extraInterest).doubleValue / 100);
        view.due = SAFE_NUMBER(self.viewModel.apiModel.duration);
        [view reloadInfos];
        [view show];
    }
}

- (void)onStatusButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0028];
    switch(self.status)
    {
        case CYFinanceDetailStatusNormal:
        {
            [self investAction];
            break;
        }
        case CYFinanceDetailStatusDisable:
        {
            break;
        }
        case CYFinanceDetailStatusNotLoggedIn:
        {
            [self showLogInAction];
            break;
        }
    }
}

#pragma mark - Private Method
- (void)refreshStatusButton
{
    if(CYStandardAuthManager.currentAuth)
    {
        if(self.viewModel)
        {
            switch(self.viewModel.status)
            {
                case CYFinanceViewModelStatusWillSale:
                {
                    NSTimeInterval timeInterval = [self.viewModel.saleDate timeIntervalSinceNow];
                    if(timeInterval < 0)
                    {
                        self.status = CYFinanceDetailStatusNormal;
                        self.statusButton.enabled = YES;
                        [self.statusButton setBackgroundImage:[UIImage imageWithColor:APP_DEFAULT_COLOR_RED size:CGSizeMake(1, 1)] forState:UIControlStateNormal];
                        [self.statusButton setTitle:@"立即投资" forState:UIControlStateNormal];
                    }
                    else
                    {
                        self.status = CYFinanceDetailStatusDisable;
                        self.statusButton.enabled = NO;
                        [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"FFC4C8") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
                        [self.statusButton setTitle:[NSString stringWithFormat:@"%@后开售", self.viewModel.saleDate.cy_financeCountDown] forState:UIControlStateNormal];
                    }
                    break;
                }
                case CYFinanceViewModelStatusOnSale:
                {
                    self.status = CYFinanceDetailStatusNormal;
                    self.statusButton.enabled = YES;
                    [self.statusButton setBackgroundImage:[UIImage imageWithColor:APP_DEFAULT_COLOR_RED size:CGSizeMake(1, 1)] forState:UIControlStateNormal];
                    [self.statusButton setTitle:@"立即投资" forState:UIControlStateNormal];
                    break;
                }
                case CYFinanceViewModelStatusFull:
                {
                    self.status = CYFinanceDetailStatusDisable;
                    self.statusButton.enabled = NO;
                    [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"CCCCCC") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
                    [self.statusButton setTitle:@"已售罄" forState:UIControlStateNormal];
                    break;
                }
                case CYFinanceViewModelStatusDone:
                {
                    self.status = CYFinanceDetailStatusDisable;
                    self.statusButton.enabled = NO;
                    [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"CCCCCC") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
                    [self.statusButton setTitle:@"已还款" forState:UIControlStateNormal];
                    break;
                }
            }
        }
        else
        {
            self.status = CYFinanceDetailStatusDisable;
            self.statusButton.enabled = NO;
            [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"CCCCCC") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
            [self.statusButton setTitle:@"正在获取数据" forState:UIControlStateNormal];
        }
    }
    else
    {
        self.status = CYFinanceDetailStatusNotLoggedIn;
        self.statusButton.enabled = YES;
        [self.statusButton setBackgroundImage:[UIImage imageWithColor:APP_DEFAULT_COLOR_RED size:CGSizeMake(1, 1)] forState:UIControlStateNormal];
        [self.statusButton setTitle:@"登录" forState:UIControlStateNormal];
    }
}


@end
